package com.neu.fragement;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.neu.R;

public class AFragment extends Fragment {

    private AViewModel mViewModel;
    private Button btnA;
    private Button btnView;
    private TextView tvA;

    public static AFragment newInstance() {
        return new AFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.a_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
      //  mViewModel = ViewModelProviders.of(this).get(AViewModel.class);

       //viewmode实例化
       mViewModel= new ViewModelProvider(requireActivity(),new ViewModelProvider.NewInstanceFactory()).get(AViewModel.class);

        // 获得viewmodel的数据
        mViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tvA.setText(s);
            }
        });

        //实例化
        tvA=getActivity().findViewById(R.id.tvA);
        btnView=getActivity().findViewById(R.id.btnView);
        btnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewModel.setText("点击按钮修改viewmodel的数据");
            }
        });



        //活動按鈕的實例
        btnA=getActivity().findViewById(R.id.btnA);
        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle=new Bundle();
                bundle.putString("a","我是從A來的。。。。");
                Navigation.findNavController(getView()).navigate(R.id.action_AFragment_to_BFragment,bundle);
            }
        });
    }

}